<?php
/**
 * Celebrio Core
 * 
 * @copyright  Copyright (c) 2011 Celebrio Software
 * @package    Celebrio
 * @subpackage Core
 */
namespace Celebrio\Core;

use \Nette\Object;

use \dibi;
use \FileNotFoundException;
use \DibiException;

/**
 * Static class provides the DDL files execution
 *
 * @author pavel
 */
abstract class DDL extends Object {

    /**
     * Executes SQL DDL (or DML, but don't use it for DML) file
     * in the database machine.
     * 
     * Every part of file finished by semicolon is executed at once. 
     * When you need to process more blocks together (for example
     * when defining triggers), use delimiter (hash sign # by default).
     * When the delimiter is found, all the code until the next delimiter
     * is executed as one query. Delimiter sign should be on 
     * the line alone, the only character.
     *
     * @param string filename
     * @param string delimiter
     * @return int count of sql commands
     */
    public static function execute($file, $delimiter = '#') {

        @set_time_limit(0); // intentionally @

        if (!dibi::isConnected()) {
            throw new DibiException(_("Dibi is not connected when trying to load the script from file."));
        }

        $handle = @fopen($file, 'r'); // intentionally @
        if (!$handle) {
            throw new FileNotFoundException(sprintf(_("Cannot open file %s."),$file));
        }

        $count = 0;
        $sql = '';
        $separator = ';';
        while (!feof($handle)) {
                $s = fgets($handle);

                if (substr(rtrim($s), -1) == $delimiter) {
                    if ($separator === ';') {
                        $separator = $delimiter;
                        continue;
                    } else {
                        $separator = ';';
                        $s = ';'; //finish the statement and execute it 5 lines below
                    }
                }

                $sql .= $s;

                if (substr(rtrim($s), -1) === $separator) {
                        dibi::nativeQuery($sql);
                        $sql = '';
                        $count++;
                }
        }
        fclose($handle);
        return $count;
    }
}